//
//  SAMemberHistoryVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/6/28.
//

#import "SAMemberHistoryVC.h"
#import "SAMemberHistoryCell.h"
#import "SASalesInvoiceListProfitAPI.h"
#import "SAMemberHistoryModel.h"
#import "SAShopSaleReturnDetailVC.h"
#import "SASaleDocumentsDetailVC.h"

@interface SAMemberHistoryVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) UILabel *balanceLab;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SASalesInvoiceListProfitAPI *salesInvoiceListProfitAPI;
@property (nonatomic, strong) NSMutableArray<SAMemberHistoryModel *> *dataMarr;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) UIView *tipView;
@property (nonatomic, strong) NSString *memberId;
@property (nonatomic, strong) UILabel *consumptionLab;

@end

@implementation SAMemberHistoryVC

-(instancetype)initWithMemberId:(NSString *)memberId {
    if (self = [super init]) {
        self.memberId = memberId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (self.salesInvoiceListProfitAPI == api) {
        if (self.currentPage == 1) {
            self.dataMarr = [SAMemberHistoryModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
            NSString *actualPrice = [NSString stringWithFormat:@"%@",data[@"data"][@"obj"][@"actualPrice"]];
            if (actualPrice && actualPrice.length > 0) {
                self.consumptionLab.text = [NSString stringWithFormat:@"消费总额:￥%0.2lf",[actualPrice doubleValue]/100];
            }
        }else {
            NSMutableArray *marr = [SAMemberHistoryModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
            for (SAMemberHistoryModel *model in marr) {
                [self.dataMarr addObject:model];
            }
        }
        [self.tableView reloadData];
        self.tipView.hidden = self.dataMarr.count > 0;
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - UITableView Delegate & DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAMemberHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAMemberHistoryCell"];
    cell.model = self.dataMarr[indexPath.section];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SAMemberHistoryModel *model = self.dataMarr[indexPath.section];
    if ([model.orderType isEqualToString:@"2"]) {
        SAShopSaleReturnDetailVC *pushVC = [[SAShopSaleReturnDetailVC alloc] initWithSaleOrderId:model.salesOrderId AndSaleOrderNo:model.salesOrderNo];
        [self.navigationController pushViewController:pushVC animated:YES];
    }else {
        SASaleDocumentsDetailVC *pushVC = [[SASaleDocumentsDetailVC alloc] initWithSaleOrderId:model.salesOrderId AndSaleOrderNo:model.salesOrderNo MerchantId:@""];
        [self.navigationController pushViewController:pushVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(55);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

-(void)loadData {
    self.salesInvoiceListProfitAPI.currentPage = self.currentPage;
    [self.salesInvoiceListProfitAPI sendRequestToServerWithActivityViewAndMask:GET];
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"历史消费"];
    self.view.backgroundColor = kBgColor;
    
    UILabel *consumptionLab = [[UILabel alloc] initWithFrame:SARectMake(26, StatusHeight, 340, 30)];
    consumptionLab.textColor = kBlackColor;
    consumptionLab.font = kFont(15);
    consumptionLab.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:consumptionLab];
    self.consumptionLab = consumptionLab;
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.tipView];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    }];
    MJRefreshAutoStateFooter *mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage ++;
        [weakSelf loadData];
    }];
    [mj_footer setTitle:@"已经到底啦~" forState:MJRefreshStateIdle];//设置闲置状态下不显示“点击或上拉加载更多”
    self.tableView.mj_footer = mj_footer;
    
    self.currentPage = 1;
    self.salesInvoiceListProfitAPI.memberId = self.memberId;
    self.salesInvoiceListProfitAPI.pageSize = 20;
    self.salesInvoiceListProfitAPI.merchantId = @"0";
    [self loadData];
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 30), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 30)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAMemberHistoryCell class] forCellReuseIdentifier:@"SAMemberHistoryCell"];
    }
    return _tableView;
}

-(SASalesInvoiceListProfitAPI *)salesInvoiceListProfitAPI {
    if (!_salesInvoiceListProfitAPI) {
        _salesInvoiceListProfitAPI = [SASalesInvoiceListProfitAPI apiWithDelegate:self];
    }
    return _salesInvoiceListProfitAPI;
}

-(NSMutableArray<SAMemberHistoryModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(UIView *)tipView {
    if (!_tipView) {
        _tipView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 30), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 30))];
        _tipView.backgroundColor = [UIColor whiteColor];
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Shop_search2"]];
        icon.frame = SARectMake(124, 106, 138, 83);
        [_tipView addSubview:icon];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + kScaleNum(20), _tipView.width, kScaleNum(20))];
        titleLab.text = @"暂无相关信息";
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = kGrayColor;
        [_tipView addSubview:titleLab];
    }
    return _tipView;
}

@end
